package org.test.java;

import static org.test.java.ShuaTa.httpRequestWithLogFile;
import static org.test.java.ShuaTa.print;
import static org.test.java.ShuaTa.sleepTime;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Thiefe implements Runnable {

	private String _sid;
	Properties props;
	private static String logFile = "thiefe.log";

	public Thiefe(String _sid, Properties props) {
		this._sid = _sid;
		this.props = props;
		if (props.containsKey("thiefeLogFile")) {
			logFile = props.getProperty("thiefeLogFile");
		}
		if (props.containsKey("shuaTaSleepTime")) {
			sleepTime = Integer.parseInt(props.getProperty("shuaTaSleepTime"));
		}
	}

	private static int getInt(Map map, String key) {
		return (Double.valueOf(map.get(key).toString())).intValue();
	}
	
	@Override
	public void run() {
		int temp = 0;
		while (true) {
			try {
				try {
					if (temp >= 1)
						Thread.sleep(sleepTime * 60 * 1000);
					temp++;
				} catch (InterruptedException e1) {
					e1.printStackTrace();
					try {
						log(e1.getMessage());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				try {
					while (true) {
						Map result = httpRequestWithLogFile(_sid, "arena.php",
								"GetThieves", "", logFile);
						int status = getInt(result, "status");
						if (status == 0)
							continue;
						Map data = (Map) result.get("data");
						int countDown = getInt(data, "Countdown");
						if (countDown > 0) {
							log("等待盗贼时间：" + countDown + "s");
							Thread.sleep(countDown * 1000);
							continue;
						}
						List thieves = (List) data.get("Thieves");
						for (Object item : thieves) {
							Map thiefe = (Map) item;
							int hPCurrent = getInt(thiefe, "HPCurrent");
							int fleeTime = getInt(thiefe, "FleeTime");
							String id = thiefe.get("UserThievesId").toString();
							if(id!=null && id.contains(".0")){
								id = id.replaceAll("\\.0", "");
							}
							if (hPCurrent > 0 && fleeTime > 0) {
								log("盗贼：" + data.toString());
								Map battleResult = httpRequestWithLogFile(_sid,
										"arena.php", "ThievesFight",
										"UserThievesId=" + id, logFile);
								log("盗贼战斗：" + battleResult.toString());
							}
						}
						break;
					}
				} catch (Exception e) {
					e.printStackTrace();
					try {
						log(e.getMessage());
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void log(String message) throws IOException {
		print(logFile, message);
	}

}
